package per.yhh.xxxtsj.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import per.yhh.xxxtsj.Utils.JWTUtils;
import per.yhh.xxxtsj.entity.Menu;
import per.yhh.xxxtsj.entity.Message;
import per.yhh.xxxtsj.entity.Token;
import per.yhh.xxxtsj.entity.User;
import per.yhh.xxxtsj.service.CategoryService;
import per.yhh.xxxtsj.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@CrossOrigin
@RestController
@RequestMapping("/")
public class MainController {
    final
    CategoryService categoryService;
    final
    UserService userService;

    public MainController(CategoryService categoryService, UserService userService) {
        this.categoryService = categoryService;
        this.userService = userService;
    }

    @GetMapping("/index")
    public String index() {
        return "hello!";
    }

    @PostMapping("/login")
    public Message login(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        String account = (String) jsonObject.get("account");
        String password = (String) jsonObject.get("password");
        User user = userService.login(account, password);
        if (user == null) return Message.failed();
        String token = JWTUtils.createToken(account);
        HttpSession session = request.getSession();
        session.setAttribute("permission", user.getPermissions());
        return Message.ok(new Token(token,user.getPermissions()));
    }

    @GetMapping("/menus")
    public Message menus(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Integer permission = (Integer) session.getAttribute("permission");
        if (permission == null) return Message.Unauthorized("未登录");
        return Message.ok(Menu.menus.values()[permission].returnMenu());
    }

    @GetMapping("/categories")
    public Message categories(@RequestParam(value = "pagenum", required = false) Integer pageNum, @RequestParam(value = "pagesize", required = false) Integer pageSize) {
        if (pageNum == null && pageSize == null) return Message.ok(categoryService.getCategories());
        return Message.ok(categoryService.getCategoriesByPage(pageNum, pageSize));
    }

}
